import React, { Component } from "react";
import logo from "../../assets/images/logo.svg";
import "./login.less";
import { Button, Form, Input, message } from "antd";
import { LockOutlined } from "@ant-design/icons";
import { UserOutlined } from "@ant-design/icons";
import { reqLogin } from "../../api";
import storageUtils from "../../utils/storageUtils";
import withRouter from "../../utils/withRouter";
import { Navigate } from "react-router-dom";

class Login extends Component {
  onFinish = async (values) => {
    console.log("Success:", values);
    const { username, password } = values;
    const res = await reqLogin(username, password);
    console.log(res);
    if (res.status === 0) {
      const user = res.data;
      // 将用户信息保存到local中 localStorage
      storageUtils.saveUser(user);
      this.props.navigate("/");
      message.success("登录成功");
    } else {
      message.error(res.msg);
    }
  };
  onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  // 自定义验证函数
  validatorPwd = (_, value) => {
    value = value ? value.trim() : "";
    if (!value) {
      return Promise.reject(new Error("密码必须输入"));
    } else if (value.length < 4) {
      return Promise.reject(new Error("密码不能小于4位"));
    } else if (value.length > 12) {
      return Promise.reject(new Error("密码不能大于12位"));
    } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
      return Promise.reject(new Error("必须是英文、数字或者下划线组成"));
    } else {
      return Promise.resolve();
    }
  };

  render() {
    const user = this.props.user;
    if (user) {
      return <Navigate to="/home" />;
    }
    return (
      <div className="login">
        <div className="login-header">
          <img src={logo} alt="" />
          <h1>React后台管理系统</h1>
        </div>
        <div className="login-content">
          <h1>用户登录</h1>
          <Form
            name="basic"
            initialValues={{
              remember: true,
            }}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              name="username"
              initialValue={"admin"}
              rules={[
                {
                  required: true,
                  whitespace: true,
                  message: "用户名是必须的!",
                },
                // { min: 4, message: "用户名不能小于4位" },
                // { max: 12, message: "用户名不能大于12位" },
                // {
                //   pattern: /^[a-zA-Z0-9_]+$/,
                //   message: "必须是英文、数字或者下划线组成",
                // },
              ]}
            >
              <Input
                prefix={<UserOutlined style={{ color: "rgba(0,0,0,.25)" }} />}
                placeholder="请输入用户名"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  validator: this.validatorPwd,
                },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: "rgba(0,0,0,.25)" }} />}
                placeholder="请输入密码"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                style={{ width: "100%" }}
                htmlType="submit"
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

export default withRouter(Login);
